<?php

namespace App\Console\Commands;

use App\Models\ServiceOrder;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\Console\Input\InputArgument;
use Swoole\WebSocket\Server;

class SwooleCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'swoole {action=start}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'this is command for swoole';

    /**
     * Create a new command instance.
     *
     * @return void
     */

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->fire();
    }

    public function fire(){
        $action = $this->argument('action');
        switch ($action){
            case 'start':
                $this->info("swoole observer started");
                $this->start();
                break;
            case 'stop':
                $this->info("stoped");
                break;
            case 'restart':
                $this->info("restarted");
                break;
            default:
                $this->error("unknown command");
        }

    }

    private function start(){
        $server = new Server('0.0.0.0', 8099, SWOOLE_PROCESS, SWOOLE_SOCK_TCP | SWOOLE_SSL);
        $key_dir = "/www/server/panel/vhost/cert/xiche.jianzhan580.com";
        $config = [
            'ssl_cert_file'=>$key_dir."/fullchain.pem",
            'ssl_key_file'=>$key_dir."/privkey.pem",
            'worker_num' => 1,
            'heartbeat_check_interval' => 60, //心跳检测
            'max_request' => 1000,
            'log_file' => storage_path("swoole/swoole.log"),
        ];
        $server->set($config);
        //监听WebSocket连接打开事件
        $server->on('open', function ($ws, $request) {

        });
        //监听WebSocket消息事件
        $server->on('message', function ($ws, $frame) {
            $data = json_decode($frame->data,true);
            if ($data['type']=='ping_admin'||$data['type']=='ping_shop'){
                $shop_id = $data['shop_id'];
                $key = $data['type']."_count_".$shop_id;
                $cacheCount = Cache::get($key);
                $newOrder = Cache::get("isNewOrder_".$shop_id, false);
                $count = ServiceOrder::query()
                    ->where("shop_id",0)
                    ->where("is_apply",0)
                    ->where("status",0)
                    ->where("shop_id",$shop_id)
                    ->count();
                $type = "oldCount";
                if (($cacheCount!==null&&$cacheCount!=$count)||($cacheCount==null&&$count)){
                    if ($newOrder){
                        $type = "newCount";
                        Cache::put("isNewOrder_".$shop_id, false);
                    }
                }
                Cache::put($key, $count);
                $ws->push($frame->fd,json_encode([
                    'type'=>$type,
                    'count'=>$count
                ]));
            }else{
                //推送给所有链接
//                foreach ($ws->connections as $fd){
//                    $ws->push($fd,json_encode($data));
//                }
            }
        });
        //监听WebSocket连接关闭事件
        $server->on('close', function ($ws, $fd) {
            echo "client-{$fd} is closed\n";
        });

        $server->start();
    }

    protected function getArguments()
    {
        return [[
            'action', InputArgument::REQUIRED, 'start|stop|restart'
        ]];
    }
}
